package com.jiuqi.common.authority.netrep.origin.util;

import java.math.BigInteger;
import java.util.Random;

public class Guid implements Cloneable{

  public static        int    GUID_SIZE = 32;
  public static        String emptyGuid="00000000000000000000000000000000";
  private static       Random rndGuid=new Random(Math.round(Math.random()*10000));
  private byte data[]=new byte[16];

  public static String newGuid(){
    Guid T=new Guid();
    T.generate();
    return T.toString();
  }

  public void generate() {

    BigInteger BI1=BigInteger.valueOf(System.currentTimeMillis());
    BigInteger BI2=new BigInteger(8*8,rndGuid);

    byte[] BA=BI1.toByteArray();
    for(int i=0;i<8-BA.length;i++) data[i]=0;
    for(int i=0;i<BA.length;i++) data[8-BA.length+i]=BA[i];

    BA=BI2.toByteArray();
    for(int i=0;i<8-BA.length;i++) data[8+i]=0;
    for(int i=0;i<BA.length;i++) if(BA.length-i<=8)data[16-BA.length+i]=BA[i];
  }

  public Object clone(){
    Guid copy = new Guid();
    copy.data = (byte[])data.clone();
    return copy;
  }

  public boolean equals(Object o){
    if(o instanceof Guid)
      return data.equals(((Guid)o).data);
    else return false;
  }

  public String toString(){
    StringBuffer str=new StringBuffer(32);
    for(int i=0;i<data.length;i++){
      int code=(data[i]>>4)&0x0F;
      str.append(JqLib.HEX_CHARS[code]);
      code=data[i]&0x0F;
      str.append(JqLib.HEX_CHARS[code]);
    }
    return new String(str);
  }

  public String tobase64(){
    int b,t;
    int i,p;
    StringBuffer s=new StringBuffer("0000000000000000000000");

    p=0;i=0;
    while(i<15){
      b=data[i++];t=b;
      b=b >>> 2 & 63;
      s.setCharAt(p++,JqLib.BASE64_CHARS[b]);
      b=data[i++];t=b;
      b=b >>> 4 & 15;t&=3;t<<=4;b|=t;
      s.setCharAt(p++,JqLib.BASE64_CHARS[b]);
      b=data[i++];t=b;
      b=b >>> 6 & 3;t&=15;t<<=2;b|=t;
      s.setCharAt(p++,JqLib.BASE64_CHARS[b]);
      t&=63;b=t;
      s.setCharAt(p++,JqLib.BASE64_CHARS[b]);
    }

    b=data[i++];t=b;
    b=b >>> 2 & 63;
    s.setCharAt(p++,JqLib.BASE64_CHARS[b]);
    b=0;t=b;
    b=b >>> 4 & 15;t&=3;t<<=4;b|=t;
    s.setCharAt(p++,JqLib.BASE64_CHARS[b]);

    return new String(s);
  }

  public static void main(String[] args){
    for( int i=0; i<10000; i++)
      System.out.println(Guid.newGuid());
  }
}